package leetcode_回溯;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 组合总和II
 * 与 39 相比，数组中的数只能使用一次
 */
public class _40 {
    List<Integer> tem = new ArrayList<>();
    List<List<Integer>> ans = new ArrayList<>();
    int[] candidates;
    int len;
    boolean[] used;

    public static void main(String[] args) {
        System.out.println(new _40().combinationSum2(new int[]{10,1,2,7,6,1,5}, 8));
    }

    public List<List<Integer>> combinationSum2(int[] candidates, int target) {
        this.candidates = candidates;
        len = candidates.length;
        used = new boolean[len];
        Arrays.sort(this.candidates);
        dfs(target, 0);
        return ans;
    }
    public void dfs(int target, int begin) {
        if (target == 0) {
            ans.add(new ArrayList<>(tem));
            return;
        }
        for (int i = begin; i < len; i++) {
            if (i > 0 && candidates[i] == candidates[i - 1] && !used[i - 1]) {
                continue;
            }
            if (candidates[i] > target) {
                break;
            }
            if (!used[i]) {
                tem.add(candidates[i]);
                used[i] = true;
                dfs(target - candidates[i], i + 1);
                used[i] = false;
                tem.remove(tem.size() - 1);
            }
        }
    }
}
